package com.bw.educate.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.educate.common.ResponseResult;
import com.bw.educate.entity.EduCourseBase;
import com.bw.educate.repository.EduCourseRepository;
import com.bw.educate.service.IEduCourseBaseService;
import com.bw.educate.util.TestImport;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 在线教育-五组
 * @since 2020-08-12
 */
@RestController
@RequestMapping("/base")
public class EduCourseBaseController {

    @Autowired
    private IEduCourseBaseService courseBaseService;

    @Autowired
    private TestImport testImport;

    @Autowired
    private EduCourseRepository courseRepository;

    @Value("${xjnfilePath}")
    private String filePath;

    /**
     * @Description:课程列表，模糊查询
     * @Author: 王文佳
     * @Date: 2020/8/15 20:21
     * @param currentPage:
     * @param pageSize:
     * @param courseBase:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @PostMapping("/list/{currentPage}/{pageSize}")
    public ResponseResult list(@PathVariable("currentPage")int currentPage,
                               @PathVariable("pageSize")int pageSize,
                               @RequestBody EduCourseBase courseBase){

        return courseBaseService.listAll(currentPage,pageSize,courseBase);
    }

   /**
    * @Description:课程推荐列表，模糊查询
    * @Author: 王文佳
    * @Date: 2020/8/17 13:00
    * @param currentPage:
    * @param pageSize:
    * @param courseBase:
    * @return: com.bw.educate.common.ResponseResult
    **/
    @PostMapping("/listRecommend/{currentPage}/{pageSize}")
    public ResponseResult listRecommend(@PathVariable("currentPage")int currentPage,
                               @PathVariable("pageSize")int pageSize,
                               @RequestBody EduCourseBase courseBase){

        return courseBaseService.listRecommend(currentPage,pageSize,courseBase);
    }

    /**
     * @Description:课程的添加
     * @Author: 王文佳
     * @Date: 2020/8/15 21:11
     * @param courseBase: 
     * @return: com.bw.educate.common.ResponseResult
     **/
    @PostMapping("/addCourse/{userId}")
    public ResponseResult addCourse(@PathVariable("userId")long userId,@RequestBody EduCourseBase courseBase){

        return courseBaseService.addCourse(userId,courseBase);
    }

    /**
     * @Description:课程的修改
     * @Author: 王文佳
     * @Date: 2020/8/15 21:11
     * @param courseBase:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @PostMapping("/updateCourse")
    public ResponseResult updateCourse(@RequestBody EduCourseBase courseBase){

        return courseBaseService.updateCourse(courseBase);
    }

    /**
     * @Description:推荐课程的修改
     * @Author: 王文佳
     * @Date: 2020/8/17 20:22
     * @param courseBase:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @PostMapping("/updateRecommend")
    public ResponseResult updateRecommend(@RequestBody EduCourseBase courseBase){

        return courseBaseService.updateRecommend(courseBase);
    }

    /**
     * @Description:修改状态
     * @Author: 李闯
     * @Date: 2020/8/25 9:51
     * @param id:
     * @param state:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @PostMapping("/updateState/{id}/{state}")
    public ResponseResult delGoods(@PathVariable long id, @PathVariable int state) {

        return courseBaseService.updateStatus(id,state);
    }

    /**
     * @Description:课程的删除
     * @Author: 王文佳
     * @Date: 2020/8/15 21:11
     * @param id:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("/deleteCourseBase/{id}")
    public ResponseResult deleteCourseBase(@PathVariable("id")int id){

        return courseBaseService.deleteCourseBase(id);
    }

    /**
     * @Description:课程推荐的删除
     * @Author: 王文佳
     * @Date: 2020/8/17 13:22
     * @param id:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("/removeRecommend/{id}")
    public ResponseResult removeRecommend(@PathVariable("id")int id){

        return courseBaseService.removeRecommend(id);
    }

    /**
     * @Description:专业一级分类列表
     * @Author: 王文佳
     * @Date: 2020/8/16 22:07
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("/parentList")
    public ResponseResult parentList(){

        return courseBaseService.parentList();
    }

    /**
     * @Description:专业一级的id查询二级分类
     * @Author: 王文佳
     * @Date: 2020/8/16 22:07
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("/childList/{id}")
    public ResponseResult ChildList(@PathVariable("id")long id){

        return courseBaseService.childList(id);
    }

    /**
     * @Description:查询当前id的课程
     * @Author: 王文佳
     * @Date: 2020/8/17 8:35
     * @param id:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("/findCourse/{id}")
    public ResponseResult findCourse(@PathVariable("id")long id){

        return courseBaseService.findCourse(id);
    }

    /**
     * @Description:查询当前id的推荐课程
     * @Author: 王文佳
     * @Date: 2020/8/17 20:15
     * @param id:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("/getByRecommendId/{id}")
    public ResponseResult getByRecommendId(@PathVariable("id")long id){

        return courseBaseService.getByRecommendId(id);
    }

    /**
     * @Description:查询未推荐课程
     * @Author: 王文佳
     * @Date: 2020/8/17 21:00
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("/searchRecommend")
    public ResponseResult searchRecommend(){

        return courseBaseService.searchRecommend();
    }

    /**
     * @Description:添加推荐课程
     * @Author: 王文佳
     * @Date: 2020/8/17 22:55
     * @param id:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("/getRecommend/{id}")
    public ResponseResult getRecommend(@PathVariable("id")long id){

        return courseBaseService.getRecommend(id);
    }

    /**
     * 文件下载接口
     */
    @GetMapping("download/{picture}")
    public void download(@PathVariable("picture") String picture, HttpServletResponse response) {

        if (null == picture) {
            return;
        }
        try {
            String bucketName = "chuang-ying";
            OSS ossClient =getOss();
            // <yourObjectName>从OSS下载文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            String objectName = filePath+picture;
            // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
            InputStream inputStream = ossObject.getObjectContent();

            byte[] b = new byte[1024];//定义每次读取输入流当中的多少字节
            int len;//记录每次读取字节流的位置

            while ((len = inputStream.read(b)) > 0) {            //将文件流写到响应输出流当中
                response.getOutputStream().write(b, 0, len);
            }

            // 关闭OSSClient。
            ossClient.shutdown();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 商品图片上传接口
     */
    @PostMapping("upload")
    public ResponseResult upload(MultipartFile file) {
        ResponseResult result = ResponseResult.SUCCESS();

        try {
            //1，获取文件后缀
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
            //2，重新定义文件名
            String fileName = UUID.randomUUID() + ext;
            //3，将文件复制到对应服务器的路径下

            String bucketName = "chuang-ying";

            // 创建OSSClient实例。
            OSS ossClient =getOss();

            // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
            File cfile = new File(file.getOriginalFilename());
            FileUtils.copyInputStreamToFile(file.getInputStream(), cfile);
            ossClient.putObject(bucketName,filePath+fileName , new FileInputStream(cfile));
            // 会在本地产生临时文件，用完后需要删除
            if (cfile.exists()) {
                cfile.delete();
            }
            // 关闭OSSClient。
            ossClient.shutdown();

            //4，将文件的存储路径返回给前端
            Map map = new HashMap();
            map.put("path", fileName);
            result.setResult(map);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("上传失败:" + e.toString());
        }
        return result;
    }

    // 创建OSSClient实例
    public OSS getOss(){
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        String accessKeyId = "LTAI4G96XgvtFw4GLTmcQJ5v";
        String accessKeySecret = "SHfhQzADRPAH8bZobaFQLyRvx4mre9";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        return ossClient;
    }

    /**
     * @Description:远程调用推荐课程
     * @Author: 周明丽
     * @Date: 2020/8/23 21:44
     * @return: java.util.List<com.bw.educate.entity.EduCourseBase>
     **/
    @GetMapping("getList")
    public List<EduCourseBase> getList(){

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("RECOMMENDED",1);
        queryWrapper.eq("COURSE_STATUS",1);
        List<EduCourseBase> list=courseBaseService.list(queryWrapper);

        return list;

    }

    /**
     * @Description:ES模糊分页查询
     * @Author: 李闯
     * @Date: 2020/8/25 8:34
     * @param size:
     * @param page:
     * @param courseBase:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @PostMapping("esList/{size}/{page}")
    public ResponseResult findAll(@PathVariable("size") Integer size,@PathVariable("page") Integer page,@RequestBody EduCourseBase courseBase){
        ResponseResult result=ResponseResult.SUCCESS();
        try {
            result.setResult(courseBaseService.eslist(size,page,courseBase));
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("查询失败");
        }
        return result;
    }

    /**
     * @Description:C端通过讲师的id展示课程信息
     * @Author: 王文佳
     * @Date: 2020/8/24 17:06
     * @param id:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("getByTeacherId/{id}")
    public List<EduCourseBase> getByTeacherId(@PathVariable("id")long id){

        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("TEACHER_ID",id);
        List<EduCourseBase> list = courseBaseService.list(queryWrapper);
        return list;
    }

    /**
     * @Description: 通过定点的id展示课程信息
     * @Author: 王文佳
     * @Date: 2020/8/26 15:11
     * @param courseBases:
     * @return: org.springframework.web.bind.annotation.RestController
     **/
    @PostMapping("getOrderById")
    public ResponseResult getOrderById(@RequestBody List<EduCourseBase> courseBases){

        return courseBaseService.getOrderById(courseBases);
    }

    /**
     * @Description:通过课程查询讲师信息
     * @Author: 王文佳
     * @Date: 2020/8/27 22:16
     * @param id:
     * @return: com.bw.educate.common.ResponseResult
     **/
    @GetMapping("/findTeacher/{id}")
    public ResponseResult findTeacher(@PathVariable("id")long id){

        return courseBaseService.findTeacher(id);
    }

}
